// pages/usercenter/member-list/index.js
const userModel = require('../../../model/user');
const {getMemberSubs, deleteMember} = require('../../../services/member/index');

Page({
  data: {
    members: [],
    filteredMembers: [],
    inviteCode: '',
    searchQuery: ''
  },
  onLoad(options) {
    const userData = userModel.getUserData();
    const userId = options.userId || userData.info.id;
    this.setData({
      inviteCode: userData.info.inviteCode,
    });
    if (!userId) {
      wx.showToast({
        title: '用户未登录',
        icon: 'error'
      });
      return;
    }

    getMemberSubs(userId)
      .then(res => {
        this.setData({ 
          members: res.CABINET_OWNER, 
          filteredMembers: res.CABINET_OWNER // 初始值
        });
      })
      .catch(() => {
        wx.showToast({
          title: '加载失败',
          icon: 'error'
        });
      });
  },
  onInviteMember() {
    wx.showToast({
      title: '功能暂未开放',
      icon: 'none'
    });
  },
  tapCabinetOwner(event) {
    const cabinetOwnerId = event.currentTarget.dataset.id; 
    wx.navigateTo({ 
      url: `/pages/usercenter/member-list/member-list?userId=${cabinetOwnerId}` 
    });
  },

  onSearchInput(event) {
    const query = event.detail.value;
    this.setData({ searchQuery: query });
    this.filterMembers();
  },

  filterMembers() {
    const query = this.data.searchQuery;
    if (!query) {
      this.setData({ filteredMembers: this.data.members });
      return;
    }


    const filtered = this.data.members.filter(member => {
      // 组合地址字段
      const fullAddress = member.shippingAddress 
        ? `${member.shippingAddress.state || ''}${member.shippingAddress.city || ''}${member.shippingAddress.addressLine1 || ''}`.trim()
        : '';
  
      return (
        (member.username && member.username.toLowerCase().includes(query)) ||
        (member.phone && member.phone.includes(query)) ||
        (member.cabinetObjId && member.cabinetObjId.includes(query)) ||
        (fullAddress && fullAddress.includes(query)) // 进行整体匹配
      );
    });

    this.setData({ filteredMembers: filtered });
  }
});
